import { geoCentroid, geoMercator, geoPath } from 'd3-geo';
import L from 'leaflet';

class PathFactory {
  constructor({
    width, height, geojson
  }) {
    const padding = 0;
    this.geojson = geojson;
    this.projection = geoMercator().fitExtent(
      [[padding, padding], [width - padding * 2, height - padding * 2]], geojson
    );
    this.pathFunc = geoPath().projection(this.projection);
  }

  getPaths() {
    // 定义地理路径生成器,使每一个坐标都会先调用此投影,才产生路径值
    return this.geojson.features.map(feature => {
      const center = this.projection(geoCentroid(feature));
      return {
        ...feature.properties,
        posi: center,
        path: this.pathFunc(feature)
      };
    });
  }

  getCityPath() {
    return this.pathFunc(this.geojson);
  }

  static getBound(geojson) {
    if (!geojson) { return []; }
    const lJson = L.geoJSON(geojson);
    const dataBounds = lJson.getBounds();
    const southWest = dataBounds.getSouthWest();
    const northEast = dataBounds.getNorthEast();
    return [
      [southWest.lat, southWest.lng],
      [northEast.lat, northEast.lng],
    ];
  }
}

export default PathFactory;
